from rest_framework.response import Response
from rest_framework.views import APIView
from meiduo_mall.utils.qq_sdk import OAuthQQ
from .models import OAuthQQUser
from meiduo_mall.utils import jwt_token
from .serializers import OAuthQQUserSerializer
from rest_framework import generics


class QQAuthUrlView(APIView):
    # 获取QQ登录的url
    def get(self,request):
        # 获取客户端的next参数
        state = request.query_params.get('next')
        # 获取授权的url地址
        oauthqq = OAuthQQ(state=state)
        login_url = oauthqq.get_qq_login_url()
        # 响应
        return Response({'login_url':login_url})



# class QQAuthOpenidView(APIView):
# generics中CreateAPIView类可以接收post请求 调用新代码 调用序列化器，进行反序列化验证，调用create方法创建
class QQAuthOpenidView(generics.CreateAPIView):
    def get(self,request):
        # 接收code  根据code获取access token
        code = request.query_params.get('code')
        try:
            # 与qq服务器交互
            oauthqq = OAuthQQ()
            # 根据code请求qq服务器获取token
            token = oauthqq.get_access_token(code)
            # 根据token请求qq服务器获取openid
            openid = oauthqq.get_openid(token)
        except:
            return Response({'message':'访问QQ服务器失败'})

        # 绑定现有帐号
        # return Response(openid)

        # 判断是否绑定现有帐号
        try:
            qq = OAuthQQUser.objects.get(openid=openid)
        except:
            # 未查询到，说明第一次授权，返回绑定页面，包含加密的openid
            #1.加密
            access_token = OAuthQQ.generate_openid_token(openid)
            #2.响应
            return Response({'access_token':access_token})
        else:
            # 查询到数据，说明已经绑定过，状态保持，返回登录成功
            # 生成状态保持的jwt
            token = jwt_token.get_token(qq.user)
            # 响应
            return Response({
                'user_id':qq.user.id,
                'username':qq.user.username,
                'token':token,
            })

    # 接收一个post的请求 绑定用户接口流程
    # def post(self,request):
        # 将openid与本网站帐号绑定
        # 1.接收数据
        # 2.验证
        # 3.根据手机号查询对象
        # 4.如果对象不存在则新建对象并绑定
        # 5.如果已存在则判断手机号是否正确
        # 6.如果正确则绑定
        # 7.如果不正确则返回错误
        # pass
    # 接收post请求 调用新代码
    serializer_class = OAuthQQUserSerializer





